import UIKit
class DrawingViewController: UIViewController, UICollectionViewDelegate,
UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var btncolorimage: UIImageView!
    @IBOutlet weak var colorcollection: UICollectionView!
    @IBOutlet weak var btnShare: UIButton!
    @IBOutlet weak var btneraser: UIButton!
    @IBOutlet weak var btncolorselector: UIButton!
    @IBOutlet weak var btnRainbow: UIButton!
    @IBOutlet weak var btnBrushsize: UIButton!
    @IBOutlet weak var slider: UISlider!

    var isColorHidden = 0

    var s_red : CGFloat = 255.0
    var s_green : CGFloat = 255.0
    var s_blue : CGFloat = 255.0
    var moveCount = 0
    var lastPoint = CGPoint.zero
    var brushSize : CGFloat = 5.0
    var inRainbowMode = true
    var ndict = NSDictionary()

    //MARK:- UIViewController Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        isColorHidden = 0
        doupdate()
        
        if UI_USER_INTERFACE_IDIOM() == .pad {
            var frame  = self.btncolorimage.frame
            frame.origin.x = self.btncolorselector.frame.origin.x + 4
            self.btncolorimage.frame = frame
        }
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }

    //MARK:- Touches Methods
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        slider.isHidden = true
        print("touches Begin");
        if let touch = touches.first{
            let point = touch.location(in: imageView);
            self.lastPoint = point;
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first{
            let point = touch.location(in: imageView);
            drawBetweenPoints(firstPoint: self.lastPoint, secondPoint: point)
            self.lastPoint = point;
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touches Ended");
        if let touch = touches.first{
            let point = touch.location(in: imageView);
            drawBetweenPoints(firstPoint: self.lastPoint, secondPoint: point);
        }
    }

    func drawBetweenPoints(firstPoint: CGPoint, secondPoint: CGPoint){
        UIGraphicsBeginImageContext(self.imageView.frame.size);
        let context = UIGraphicsGetCurrentContext();

        self.imageView.image?.draw(in: CGRect(x: 0, y: 0, width : self.imageView.frame.size.width, height: self.imageView.frame.height))
        //CGContextMoveToPoint(context, self.lastPoint.x, self.lastPoint.y);
        context?.move(to: firstPoint)
        context?.addLine(to: secondPoint)
        if inRainbowMode {
            randomTapped(UIButton())
            context?.setStrokeColor(red: self.s_red, green: self.s_green, blue: self.s_blue, alpha: 1)
            context?.setLineWidth(brushSize)
            context?.setLineCap(.round)
            context?.strokePath()
        } else {
            context?.setStrokeColor(red: self.s_red/255, green: self.s_green/255, blue: self.s_blue/255, alpha: 1)
                context?.setLineWidth(brushSize)
            context?.setLineCap(.round)
            context?.strokePath()
        }

        self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }

    //MARK:- CollectionView delegate Methods
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return constants().colorarr.count
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if UI_USER_INTERFACE_IDIOM() == .pad {
            return CGSize(width: 80, height: 80)
        }
        return CGSize(width: (constants().SCREENSIZE.width - 75)/6, height: (constants().SCREENSIZE.width - 75)/6)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath)
        cell.layer.masksToBounds = true
        if UI_USER_INTERFACE_IDIOM() == .pad {
            cell.layer.cornerRadius = 40.0
        } else {
            cell.layer.cornerRadius = ((constants().SCREENSIZE.width - 75)/6)/2
        }

        ndict = constants().colorarr.object(at: indexPath.row)as! NSDictionary
        let nred =  NumberFormatter().number(from:  ndict.value(forKey: "red") as! String)
        let nblue = NumberFormatter().number(from: ndict.value(forKey: "blue") as! String)
        let ngreen = NumberFormatter().number(from: ndict.value(forKey: "green")as! String)
        let sred = nred as! CGFloat
        let sblue = nblue as! CGFloat
        let sgreen = ngreen as! CGFloat
        let uColor = UIColor(red: sred/255, green: sgreen/255, blue: sblue/255, alpha: 1)
        cell.backgroundColor = uColor

        let cellImage = cell.viewWithTag(100) as! UIImageView
        if uColor == UIColor(red: self.s_red/255, green: self.s_green/255, blue: self.s_blue/255, alpha: 1) {
            cellImage.isHidden = false
        } else {
            cellImage.isHidden = true
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         ndict = constants().colorarr.object(at: indexPath.row)as! NSDictionary
        let mred =  NumberFormatter().number(from:  ndict.value(forKey: "red") as! String)
        let mblue = NumberFormatter().number(from: ndict.value(forKey: "blue") as! String)
        let mgreen = NumberFormatter().number(from: ndict.value(forKey: "green")as! String)
        self.s_red = mred as! CGFloat
        self.s_blue = mblue as! CGFloat
        self.s_green = mgreen  as! CGFloat
        btncolorimage.backgroundColor = UIColor(red: self.s_red/255, green: self.s_green/255, blue: self.s_blue/255, alpha: 1)
        var frame = self.colorcollection.frame
        frame.origin.y = constants().SCREENSIZE.height
        self.isColorHidden = 0
        UIView.animate(withDuration: 0.15, animations: {
            self.colorcollection.frame = frame
        }) { (true) in
            self.colorcollection.isHidden = true
        }
        colorcollection.deselectItem(at: indexPath, animated: false)
        self.colorcollection.reloadData()
    }

    //MARK:- IBAction Methods
    @IBAction func doshare() {
        if self.imageView.image == nil {
            return
        }
        let drawing = self.imageView.image!
        let activityViewController = UIActivityViewController(activityItems: [drawing], applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view
        self.present(activityViewController, animated: true, completion: nil)
    }

    @IBAction func randomTapped(_ sender: UIButton) {
        inRainbowMode = true
        print("random color selected");
        self.s_red = CGFloat(arc4random_uniform(256)) / 255;
        self.s_green = CGFloat(arc4random_uniform(256)) / 255;
        self.s_blue = CGFloat(arc4random_uniform(256)) / 255;
    }

    @IBAction func doColor() {
        slider.isHidden = true
        if self.isColorHidden == 0 {
            inRainbowMode = false
            colorcollection.isHidden = false
            self.isColorHidden = 1
            var frame = self.colorcollection.frame
            frame.origin.y = constants().SCREENSIZE.height - 160
            UIView.animate(withDuration: 0.15, animations: {
                self.colorcollection.frame = frame
            });
        } else {
            self.isColorHidden = 0
            var frame = self.colorcollection.frame
            frame.origin.y = constants().SCREENSIZE.height
            UIView.animate(withDuration: 0.15, animations: {
                self.colorcollection.frame = frame
            });
        }
        self.colorcollection.reloadData()
    }

    @IBAction func doslide() {
        self.isColorHidden = 0
        var frame = self.colorcollection.frame
        frame.origin.y = constants().SCREENSIZE.height
        UIView.animate(withDuration: 0.15, animations: {
            self.colorcollection.frame = frame
        });

        if slider.isHidden == true {
            slider.isHidden = false
        } else {
            slider.isHidden = true
        }
    }

    @IBAction func sliderValueChanged(_ sender: UISlider) {
        self.brushSize = CGFloat(sender.value);
        
    }

    @IBAction func doerase() {
        erase()
    }
    
    
    @IBAction func dismissBtn(_ sender: UIButton) {
        
        self.customController(title: "Are you sure?", message: "You are going to exit the Black pad drawing screen.")
        
        
    }
    
    func customController(title:String, message:String) {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Yes", style: UIAlertAction.Style.default) {
            UIAlertAction in
            NSLog("OK Pressed")
            self.dismiss(animated: false, completion: nil)
        }
        let cancelAction = UIAlertAction(title: "No", style: UIAlertAction.Style.cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
        
    }
    
    //MARK:- Other Methods
    func erase() {
        self.imageView.image = nil
    }

    func doupdate() {
        colorcollection.isHidden = true
        btncolorselector.layer.masksToBounds = true
        btncolorselector.layer.cornerRadius  = 10
        btncolorimage.layer.masksToBounds = true
        btncolorimage.layer.cornerRadius = 20
        btncolorimage.backgroundColor = UIColor.white
        slider.isHidden = true
        inRainbowMode = false
        self.s_red = 255.0
        self.s_blue = 255.0
        self.s_green = 255.0
        self.colorcollection.reloadData()
    }
}
